package com.wj.utils;

import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.csource.utils.FdfsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * FastDFS工具类
 *
 * @author wj
 * @since 2022-03-05
 */
public class FastDFSUtil {

    public static final Logger logger = LoggerFactory.getLogger(FdfsUtil.class);

    static {
        //ClientGlobal.init 方法会读取配置文件，并初始化对应的属性
        try {
            String path = new ClassPathResource("fastdfs.conf").getFile().getAbsolutePath();
            ClientGlobal.init(path);
        } catch (Exception e) {
            logger.error("初始化fastDFS失败");
        }
    }

    /**
     * 获取文件访问路径
     *
     * @return
     */
    public static String getTrackerUrl(){
        TrackerServer trackerServer = getTrackerServer();
        return "http://"+trackerServer.getInetSocketAddress().getHostName()+":8888";
    }

    /**
     * 删除文件
     *
     * @param groupName
     * @param remoteFileName
     */
    public static void deleteFile(String groupName,String remoteFileName){
        StorageClient storageClient = getStorageClient();
        try {
            int i = storageClient.delete_file(groupName, remoteFileName);
        } catch (Exception e) {
            logger.error("文件下载失败====>{}",e.getMessage());
        }
    }

    /**
     * 文件下载
     *
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static InputStream downloadFile(String groupName,String remoteFileName){
        StorageClient storageClient = getStorageClient();
        try {
            byte[] bytes = storageClient.download_file(groupName, remoteFileName);
            return new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            logger.error("文件下载失败====>{}",e.getMessage());
        }
        return null;
    }

    /**
     * 获取远程文件信息
     *
     * @param groupName
     * @param remoteFileName
     * @return
     */
    public static FileInfo getFileInfo(String groupName,String remoteFileName){
        StorageClient storageClient = getStorageClient();
        try {
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (Exception e) {
            logger.error("获取文件信息失败====>{}",e.getMessage());
        }
        return null;
    }

    /**
     * 上传文件
     *
     * @param multipartFile
     * @return
     */
    public static String uploadFile(MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        StringBuffer sb = new StringBuffer();
        StorageClient storageClient = getStorageClient();
        try {
            String[] res = storageClient.upload_file(multipartFile.getBytes(),
                    filename.substring(filename.lastIndexOf(".") + 1), null);
            for (String re : res) {
                sb.append("/");
                sb.append(re);
            }
        } catch (Exception e) {
            logger.error("上传文件失败====》" + filename, e.getMessage());
        }
        if (sb.length() == 0) {
            logger.error("上传文件失败错误码====》" + storageClient.getErrorCode());
        }
        logger.info("上传文件成功====>" + filename + "\t path：" + sb.toString());
        return sb.toString();
    }

    /**
     * 获取StorageClient客户端
     *
     * @return
     */
    private static StorageClient getStorageClient() {
        TrackerServer trackerServer = getTrackerServer();
        return new StorageClient(trackerServer);
    }

    /**
     * 获取TrackerServer服务器
     *
     * @return
     */
    private static TrackerServer getTrackerServer() {
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = null;
        try {
            trackerServer = trackerClient.getTrackerServer();
        } catch (IOException e) {
            logger.error("获取trackerServer失败=====>{}", e.getMessage());
        }
        return trackerServer;
    }

}
